package com.heifeng.cloudshelf.base;

import android.app.Activity;
import android.content.Context;
import android.os.Build;
import android.os.StrictMode;
import androidx.multidex.MultiDexApplication;
import androidx.appcompat.app.AppCompatDelegate;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.WindowManager;


import com.ansen.http.entity.HttpConfig;
import com.ansen.http.net.HTTPCaller;
import com.heifeng.cloudshelf.constants.HTTPConstants;
import com.heifeng.cloudshelf.di.component.AppComponent;
import com.heifeng.cloudshelf.di.component.DaggerAppComponent;
import com.heifeng.cloudshelf.di.module.AppModule;
import com.heifeng.cloudshelf.network.NetClient;
import com.heifeng.cloudshelf.push.JpushUtils;
import com.heifeng.cloudshelf.utils.WifiUtils;
import com.orhanobut.hawk.Hawk;
import com.tencent.bugly.crashreport.CrashReport;

import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.HashSet;
import java.util.Set;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;


/**
 * Created by codeest on 2016/8/2.
 */
public class MyApp extends MultiDexApplication {

    private static MyApp instance;
    public static AppComponent appComponent;
    private Set<Activity> allActivities;

    public static int SCREEN_WIDTH = -1;
    public static int SCREEN_HEIGHT = -1;
    public static float DIMEN_RATE = -1.0F;
    public static int DIMEN_DPI = -1;


    static {
        AppCompatDelegate.setDefaultNightMode(
                AppCompatDelegate.MODE_NIGHT_NO);
    }

    public static synchronized MyApp getInstance() {
        return instance;
    }

    //dagger2
    public static AppComponent getAppComponent() {
        if (appComponent == null) {
            appComponent = DaggerAppComponent
                    .builder()
                    .appModule(new AppModule(instance))
                    .build();
        }
        return appComponent;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;

//        ExceptionHelper.getInstance().init(getApplicationContext());

        initError();


        //初始化屏幕宽高
        getScreenSize();

        //初始化第三方
        initThirdParty();


        initLoginData();

        handleSSLHandshake();


        BaseActivity.setHideKeyboardTouchOutsideEnabled(true);
        SimpleActivity.setHideKeyboardTouchOutsideEnabled(true);


        // android 7.0系统解决拍照的问题，不推荐
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
            StrictMode.setVmPolicy(builder.build());
        }
    }

    private void initError() {
        CrashReport.UserStrategy userStrategy = new CrashReport.UserStrategy(this);
        userStrategy.setAppChannel("APP");
        userStrategy.setAppPackageName("com.heifeng.haolaike");
        userStrategy.setAppVersion("v1.0");
        CrashReport.initCrashReport(this,"aa0d39c0fd",false,userStrategy);

    }

    //初始化请求配置
    public void initialize() {

        HttpConfig httpConfig = new HttpConfig();
        httpConfig.setAgent(true);//有代理的情况能不能访问
        httpConfig.setDebug(true);//是否debug模式 如果是debug模式打印log
        httpConfig.setTagName("ansen");//打印log的tagname

        //可以添加一些公共字段 每个接口都会带上
        httpConfig.addCommonField("pf", "android");
        httpConfig.addCommonField("version_code", "1");

        //初始化HTTPCaller类
        HTTPCaller.getInstance().setHttpConfig(httpConfig);
    }

    private void initThirdParty() {
        Hawk.init(getApplicationContext()).build();
        initialize();
        JpushUtils.init(getApplicationContext());
        //设置JPush的设备别名
        HTTPConstants.macAddress = WifiUtils.getMacAddress(this).replaceAll(":", "");
        JpushUtils.setAlias(getApplicationContext(), HTTPConstants.macAddress);

    }

    private void initLoginData() {
        if (null != Hawk.get(HTTPConstants.CLIID_KEY)) {
            NetClient.cliId = Hawk.get(HTTPConstants.CLIID_KEY);
        }
        if (null != Hawk.get(HTTPConstants.TOKEN_KEY)) {
            NetClient.token = Hawk.get(HTTPConstants.TOKEN_KEY);
        }
        if (null != Hawk.get(HTTPConstants.USER_ID_KEY)) {
            HTTPConstants.userId = Hawk.get(HTTPConstants.USER_ID_KEY);
        }
        if (null != Hawk.get(HTTPConstants.CITY_KEY)) {
            HTTPConstants.city = Hawk.get(HTTPConstants.CITY_KEY);
        }
        if (!TextUtils.isEmpty(NetClient.cliId) && !TextUtils.isEmpty(NetClient.token)) {
            HTTPConstants.isLogined = true;
        } else {
            HTTPConstants.isLogined = false;
        }
    }

    public void addActivity(Activity act) {
        if (allActivities == null) {
            allActivities = new HashSet<>();
        }
        allActivities.add(act);
    }

    public void removeActivity(Activity act) {
        if (allActivities != null) {
            allActivities.remove(act);
        }
    }

    /**
     * 忽略https的证书校验
     * 避免Glide加载https图片报错：
     * javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
     */
    public void handleSSLHandshake() {
        try {
            TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
                public X509Certificate[] getAcceptedIssuers() {
                    return new X509Certificate[0];
                }

                @Override
                public void checkClientTrusted(X509Certificate[] certs, String authType) {
                }

                @Override
                public void checkServerTrusted(X509Certificate[] certs, String authType) {
                }
            }};

            SSLContext sc = SSLContext.getInstance("TLS");
            // trustAllCerts信任所有的证书
            sc.init(null, trustAllCerts, new SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
            HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });
        } catch (Exception ignored) {
        }
    }

    public void exitApp() {
        if (allActivities != null) {
            synchronized (allActivities) {
                for (Activity act : allActivities) {
                    act.finish();
                }
            }
        }
        android.os.Process.killProcess(android.os.Process.myPid());
        System.exit(0);
    }

    public void getScreenSize() {
        WindowManager windowManager = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics dm = new DisplayMetrics();
        Display display = windowManager.getDefaultDisplay();
        display.getMetrics(dm);
        DIMEN_RATE = dm.density / 1.0F;
        DIMEN_DPI = dm.densityDpi;
        SCREEN_WIDTH = dm.widthPixels;
        SCREEN_HEIGHT = dm.heightPixels;
        if (SCREEN_WIDTH > SCREEN_HEIGHT) {
            int t = SCREEN_HEIGHT;
            SCREEN_HEIGHT = SCREEN_WIDTH;
            SCREEN_WIDTH = t;
        }
    }
}
